/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "list.h"
#include "set.h"
#include "output-mode.h"
#include "logs-show.h"

static OutputMode arg_output = OUTPUT_SHORT;
static const char *arg_directory = NULL;

int main(int argc, char *argv[]) {

	bool previous_boot_id_valid = false, first_line = true, ellipsized = false, need_seek = false;
	_cleanup_(sd_journal_closep) sd_journal *j = NULL;
	sd_id128_t previous_boot_id;
	int n_shown = 0, r, poll_fd = -1;

	if (argc < 2){
		printf("Journal-Error: you must specify journal file directory.\n");
		return 0;
	}

	arg_directory = argv[1];
	printf("Directory is %s.\n", arg_directory);

	r = sd_journal_open_directory(&j, arg_directory, 0);

	if (r < 0) {
		printf("Journal-Error: failed to open %s\n", arg_directory);
		goto finish;
	} else {
		printf("Journal-Info: open %s successfully.\n", arg_directory);
    }
	FILE *fout;
	fout = fopen("journal.txt","w");
	if (!fout){
		printf("Journal-Info: cannot open journal.txt for writing.\n");
		goto finish;
	}
	r = sd_journal_seek_head(j);
	if (r < 0) {
		printf("Journal-Error: failed to seek to head.\n");
		goto finish;
	}
	r = sd_journal_next(j);
	if (r < 0) {
		printf("Journal-Error: failed to iterate through journal.\n");
		goto finish;
	}
	if (r == 0) need_seek = true;

	while (1) {
		int flags;
		size_t highlight[2] = {0};
		if (need_seek) {
		r = sd_journal_next(j);
		if (r < 0) {
			printf("Journal-Error: failed to iterate through journal.\n");
			goto finish;
		}
		if (r == 0)
			break;
		}
		sd_id128_t boot_id;
		r = sd_journal_get_monotonic_usec(j, NULL, &boot_id);
		if (r >= 0) {
			previous_boot_id = boot_id;
			previous_boot_id_valid = true;
		}
		flags = 1;
		r = show_journal_entry(fout, j, arg_output, 0, flags, NULL, 
							highlight, &ellipsized);
		need_seek = true;
		if (r == -EADDRNOTAVAIL){
			break;
		} else if (r < 0) {
			goto finish;
		}
		n_shown++;
	}
	/* fflush(stdout); */
finish:
	printf("Journal-Info: parsing journal file successfully.\n");
	fclose(fout);
	return 0;
}

